using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Application.DTOs;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;

namespace JGSY.CMS.LowCode.Platform.Application.Services
{
    /// <summary>
    /// 安全事件应用服务实现
    /// </summary>
    public class SecurityEventAppService : ISecurityEventAppService
    {
        private readonly ILogger<SecurityEventAppService> _logger;
        private static readonly List<SecurityEventDto> _securityEvents = new();
        private static long _nextId = 1;

        public SecurityEventAppService(ILogger<SecurityEventAppService> logger)
        {
            _logger = logger;
            InitializeSampleData();
        }

        public async Task<IEnumerable<SecurityEventDto>> GetAllAsync()
        {
            try
            {
                await Task.Delay(10);
                return _securityEvents.OrderByDescending(x => x.EventTime);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting all security events");
                throw;
            }
        }

        public async Task<SecurityEventDto?> GetByIdAsync(long id)
        {
            try
            {
                await Task.Delay(10);
                return _securityEvents.FirstOrDefault(x => x.Id == id);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting security event by id {Id}", id);
                throw;
            }
        }

        public async Task AddAsync(SecurityEventDto dto)
        {
            try
            {
                dto.Id = _nextId++;
                dto.EventTime = DateTime.UtcNow;
                
                _securityEvents.Add(dto);
                
                _logger.LogInformation("Security event created successfully: {Id} - {Type}", dto.Id, dto.Type);
                await Task.Delay(10);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating security event");
                throw;
            }
        }

        public async Task UpdateAsync(long id, SecurityEventDto dto)
        {
            try
            {
                var existing = _securityEvents.FirstOrDefault(x => x.Id == id);
                if (existing == null)
                    throw new ArgumentException($"Security event with id {id} not found");

                existing.Type = dto.Type;
                existing.Description = dto.Description;
                existing.UserId = dto.UserId;
                existing.EventTime = dto.EventTime;

                _logger.LogInformation("Security event updated successfully: {Id} - {Type}", id, existing.Type);
                await Task.Delay(10);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating security event {Id}", id);
                throw;
            }
        }

        public async Task DeleteAsync(long id)
        {
            try
            {
                var existing = _securityEvents.FirstOrDefault(x => x.Id == id);
                if (existing == null)
                {
                    _logger.LogWarning("Security event with id {Id} not found for deletion", id);
                    return;
                }

                _securityEvents.Remove(existing);
                _logger.LogInformation("Security event deleted successfully: {Id}", id);
                await Task.Delay(10);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error deleting security event {Id}", id);
                throw;
            }
        }

        private void InitializeSampleData()
        {
            if (_securityEvents.Any()) return;

            _securityEvents.AddRange(new List<SecurityEventDto>
            {
                new SecurityEventDto
                {
                    Id = _nextId++,
                    Type = "LoginFailure",
                    Description = "用户多次登录失败",
                    UserId = "1001",
                    EventTime = DateTime.UtcNow.AddHours(-2)
                },
                new SecurityEventDto
                {
                    Id = _nextId++,
                    Type = "UnauthorizedAccess",
                    Description = "尝试访问未授权资源",
                    UserId = "1002",
                    EventTime = DateTime.UtcNow.AddHours(-6)
                },
                new SecurityEventDto
                {
                    Id = _nextId++,
                    Type = "SuspiciousActivity",
                    Description = "检测到异常行为模式",
                    UserId = "1003",
                    EventTime = DateTime.UtcNow.AddMinutes(-30)
                }
            });
        }
    }
}
